package com.duleme.service.impl;

import com.duleme.dao.BookDao;
import com.duleme.dao.OrderDao;
import com.duleme.dao.ShoppingCartDao;
import com.duleme.entity.Book;
import com.duleme.entity.Order;
import com.duleme.entity.Shop;
import com.duleme.entity.ShoppingCart;
import com.duleme.service.CartService;

import java.util.*;

public class CartServiceImpl implements CartService {
    ShoppingCartDao cartDao = new ShoppingCartDao();
    OrderDao orderDao = new OrderDao();
    BookDao bookDao = new BookDao();
    @Override
    public Boolean addBook2Cart(int userID, Book book, int count) {
        if (cartDao.checkBookExist(userID,book)){
            return cartDao.addShopingBook(userID,book,count);
        }else {
            if (cartDao.insertShoppingBook(userID,book)){
                return cartDao.addShopingBook(userID,book,count);
            }else {
                return false;
            }
        }
    }

    @Override
    public Boolean deleteBookFCart(int userID, Book book) {
        if (cartDao.checkBookExist(userID,book)){

            return cartDao.deleteShoppingBook(userID,book);
        }else {
            return false;
        }
    }

    @Override
    public ShoppingCart getBookCart(int userID) {
        return cartDao.getShoppingBook(userID);
    }

    @Override
    public Boolean placeOrder(int userID, List<Book> list,int deliveryID) {
        Map<Integer,Integer> map = new HashMap<>();
        for (Book b:list){
            if (map.containsKey(b.getBookId())){
                System.out.println("有重复的");
                Integer i = map.get(b.getBookId());
                i+=1;
                map.put(b.getBookId(),i);
            }else {
                map.put(b.getBookId(),1);
            }
        }
        List<Book> books = new ArrayList<>();
        List<Integer> shops = new ArrayList<>();
        System.out.println("placeOrder:"+map.size());
        for(Map.Entry<Integer, Integer> entry : map.entrySet()){
            cartDao.deleteBuyBook(userID,bookDao.findBookByBookId(entry.getKey()),entry.getValue());
            books.add(bookDao.findBookByBookId(entry.getKey()));
        }
        for (Book b: books){
            if (!shops.contains(b.getShopId())){
                shops.add(b.getShopId());
            }
        }
        //System.out.println(shops.get(1));
        for (Integer i:shops){
            Order order = new Order();
            order.setCreateTime(new Date());
            order.setDeliveryID(deliveryID);
            order.setOrderState(1);
            order.setShopID(i);
            order.setUserID(userID);
            for (Book b:list){
                if (b.getShopId()==i){
                    order.addBook(b);
                }
            }
            orderDao.initOrderItem(order);
        }
        return true;
    }
}
